//
//  ProfileEditNameView.swift
//  KoiAccounting
//
//  Created by 纪洪文 on 12.04.25.
//

import SwiftUI

struct ProfileEditNameView: View {
    
    @Environment(\.presentationMode) var presentationMode
    @StateObject var viewModel = ProfileEditNameViewModel()
    @Environment(\.presentToast) var presentToast
    
    private let maxLenght = 24
    
    @State var nickname: String = ""
    var body: some View {
        VStack (alignment: .leading){
            TextField("请输入昵称", text: $nickname)
                .onChange(of: nickname) { value in
                    if value.count > 24 {
                        nickname = String(value.prefix(maxLenght))
                    }
                }
                .padding(EdgeInsets(top: 20, leading: 16, bottom: 20, trailing: 16))
                .background(Color.koiColorBackgroundItem)
                .cornerRadius(16)
                .padding(.top, 20)
            Text("请设置2-24个字符")
                .font(.system(size: 13))
                .foregroundColor(Color.koiColorTitleSecond)
                .padding(.top, 6)
                .padding(.leading, 10)
            Spacer()
        }
        .padding(.horizontal, 20)
        .navigationBarBackButtonHidden()
        .toolbar {
            ToolbarItem(placement: .navigationBarLeading) {
                Button (action:{
                    presentationMode.wrappedValue.dismiss()
                }) {
                    Image(systemName: "chevron.left").foregroundColor(Color.koiColorTitle)
                }
            }
        }
        .navigationBarTitle(Text("编辑昵称"), displayMode: .inline)
        .navigationBarItems(trailing: Button(action:{
            // 确定修改昵称
        }){
            Button(action:nicknameModify) {
                Text("确定").font(.system(size: 14)).foregroundColor(Color.koiColorPrimary)
            }
        })
        .onChange(of: viewModel.state) { value in
            if value == "" {
                return
            }
            if value == "success" {
                presentToast(.init(message: "修改成功"))
                presentationMode.wrappedValue.dismiss()
            } else {
                presentToast(.init(message: value))
            }
            viewModel.state = ""
        }
    }
    
    private func nicknameModify() {
        viewModel.nicknameModify(nickname: nickname)
    }
}

#Preview {
    ProfileEditNameView()
}
